package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.util.PasswordUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class LoginController {
    @Autowired
    UserService userService;

    @RequestMapping(value = "/page/{page}", method = RequestMethod.GET)
    public String welcome(@PathVariable(value = "page") String page) {
        return page;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestParam String name,
                           @RequestParam String password,
                           Model model) {
        userService.createUser(name, password);
        model.addAttribute("name", name);
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam String name,
                           @RequestParam String password,
                           Model model) {
        UsernamePasswordToken token = new UsernamePasswordToken(password, name);

        Subject subject = SecurityUtils.getSubject();
        subject.login(token);

        if (subject.isAuthenticated()) {
            return "success";
        } else {
            model.addAttribute("login_ifo", "登录失败");
            return "/login";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String user() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        return user.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    @RequiresAuthentication
//    @RequiresPermissions(value = "a.b.c")
    public String testAuthc() {
        Subject subject = SecurityUtils.getSubject();
        Boolean flag = subject.isAuthenticated();
        return "auth-test";
    }
}
